import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  Route, Switch, useHistory, useRouteMatch,
} from 'react-router-dom';
import Done from './pages/done/index';
import Plan from './pages/plan/index';
import {
  SubTab, SubTabContainer, SubTabLi, Main,
} from './style';

export default function PointsAndBonus() {
  const history = useHistory();
  const { path } = useRouteMatch();
  const dispatch = useDispatch();
  const subTabList = useSelector((state: any) => state.getIn(['PointsAndBonus', 'subTabList']));
  const navbarList = useSelector((state: any) => state.getIn(['App', 'navbarList']));

  function handleClickSubTabList(i: {
    id: number;
    title: string;
    get: Function;
    url: string;
  }) {
    const toRoute = i.get('url');
    const updatedSubTabList = subTabList.map(
      (item: { id: number; title: string; set: Function; get: Function }) => {
        if (item.get('id') === i.get('id')) {
          return item.set('active', true);
        }
        return item.set('active', false);
      },
    );
    dispatch({
      type: 'updateSubTabList',
      value: updatedSubTabList,
    });
    if (i.get('id') === 2) {
      dispatch({
        type: 'updateNavBarList',
        value: navbarList.map((item: any) => {
          if (item.get('id') === 1) {
            return item.set('url', '/app/pointsAndBonus/plan');
          }
          return item;
        }),
      });
    }
    history.push({
      pathname: toRoute,
    });
  }
  return (
    <>
      <SubTabContainer>
        <SubTab>
          <ul>
            {subTabList.map(
              (item: {
                id: number;
                title: string;
                get: Function;
                url: string;
              }) => (
                <SubTabLi
                  key={item.get('id')}
                  onClick={() => handleClickSubTabList(item)}
                  active={item.get('active')}
                >
                  <span>{item.get('title')}</span>
                </SubTabLi>
              ),
            )}
          </ul>
        </SubTab>
      </SubTabContainer>
      <Main>
        <Switch>
          <Route path={`${path}/plan`}>
            <Plan />
          </Route>
          <Route path={`${path}`}>
            <Done />
          </Route>
        </Switch>
      </Main>
    </>
  );
}
